{% extends "layout.html" %}
{% block flash %}
<div id="spinning_success" class="row-fluid text-center" style="display:none;">
    <div class="alert alert-info"><img id="img-spinner" src="{{ url_for('static', filename='css/libs/images/loading-icon.gif') }}"/></div>
</div>
{% endblock %}

{% block header %}
<style>
  .metadata-provider-item {
    display: flex;
    align-items: center;
    padding: 8px 12px;
    margin: 5px 0;
    background-color: #2a3441;
    border: 1px solid #555;
    border-radius: 4px;
    cursor: move;
    user-select: none;
    transition: background-color 0.2s ease;
  }
  
  .metadata-provider-item:hover {
    background-color: #3a4451;
  }
  
  .metadata-provider-item.dragging {
    opacity: 0.5;
    background-color: #2a3441;
    z-index: 1000;
    transform: rotate(2deg);
    box-shadow: 0 4px 8px rgba(0,0,0,0.3);
  }
  
  .metadata-provider-drag-handle {
    margin-right: 10px;
    color: #ffc200;
    font-size: 16px;
    font-weight: 900;
}
  
  .metadata-provider-name {
    flex-grow: 1;
    color: #fff;
  }
  
  .metadata-provider-disabled {
    color: #888;
    font-style: italic;
  }
  
  /* Prevent drag operations from affecting page styling */
  #metadata_provider_list_outer {
    position: relative;
    isolation: isolate;
    contain: layout style;
    border: 1px solid #444;
    border-radius: 4px;
    padding-inline: 30px;
    background-color: #151e2680;
    width: -webkit-fill-available;
    padding-top: 20px;
    padding-bottom: 10px;
  }
  
  /* Prevent dragover effects from affecting the page */
  body.drag-active {
    overflow: hidden;
  }
  
  /* Completely override any browser drag effects */
  .metadata-provider-item::-webkit-drag-placeholder {
    opacity: 0 !important;
  }
  
  .metadata-provider-item:-moz-drag-over {
    background-color: transparent !important;
  }
  
  /* Prevent any global styles from being affected during drag */
  body:has(.metadata-provider-item.dragging) {
    filter: none !important;
    backdrop-filter: none !important;
    opacity: 1 !important;
  }
  
  /* Ensure drag doesn't affect parent containers */
  .discover,
  .settings-container {
    filter: none !important;
    backdrop-filter: none !important;
    opacity: 1 !important;
  }
  
  .metadata-provider-item * {
    pointer-events: none;
  }

  div#metadata_provider_enabled_list {
    border: 1px solid #444;
    border-radius: 4px;
    padding: 10px;
    background-color: #151e2680;
    display: flex;
    flex-wrap: wrap;
    column-gap: 12px;
  }

  div#metadata_provider_enabled_list > div > input {
    margin: 5px;
  }
  div#metadata_provider_enabled_list > div > label {
    padding: 4px;
    margin-bottom: 0px;
    margin-left: 10px;
  }

  .provider_enable_item {
      display: flex;
      align-items: center;
      padding: 6px 10px;
      margin: 4px 0px;
      background-color: rgba(21, 30, 38, 0.5);
      border-radius: 4px;
      flex-basis: calc(50% - 6px);
  }

</style>
{% endblock %}

{% block body %}
<div class="discover">
  <h2>{{title}}</h2>
  <form action="{{ url_for('cwa_settings.set_cwa_settings')}}" method="post">
    <div class="settings-container" style="margin-top: 3rem;">
      <h4 class="settings-section-header">{{_('Enable/Disable Calibre-Web Automated Services')}}</h4>
      
      {% if cwa_settings['auto_convert'] %}
      <input type="checkbox" id="auto_convert" name="auto_convert" value="True" checked style="accent-color: var(--color-secondary);" data-toggle="tooltip"data-placement="right" data-html="true" title="Placeholder">
      {% else %}
      <input type="checkbox" id="auto_convert" name="auto_convert" value="True" style="accent-color: var(--color-secondary);" data-toggle="tooltip" data-placement="right" data-html="true" title="Placeholder">
      {% endif %}
      <label for="auto_convert" style="padding-left: 10px;">{{_('Enable CWA Auto-Convert')}}</label><br>
      <p class="cwa-settings-tooltip">
        {{_('On by default, when active all ingested books will automatically be converted to the target format specified below (epub by default) 
        <em>EXCEPT</em> those you have specifically told CWA to ignore below.') | safe }}
      </p>

      {% if cwa_settings['auto_metadata_enforcement'] %}
      <input type="checkbox" id="auto_metadata_enforcement" name="auto_metadata_enforcement" value="True" checked style="accent-color: var(--color-secondary);" data-toggle="tooltip" data-placement="right" data-html="true" title="Placeholder">
      {% else %}
      <input type="checkbox" id="auto_metadata_enforcement" name="auto_metadata_enforcement" value="True" style="accent-color: var(--color-secondary);" data-toggle="tooltip" data-placement="right" data-html="true" title="Placeholder">
      {% endif %}
      <label for="auto_metadata_enforcement" style="padding-left: 10px;">{{_('Enable CWA Automatic Cover & Metadata Enforcement Service')}}</label><br>
      <p class="cwa-settings-tooltip">
        {{_('On by default, when active, whenever the Metadata and/or Cover Image is edited in the Web UI, the CWA Metadata Enforcement service 
        will then apply those changes the ebook files themselves. Normally in Stock CW or when this setting is disabled, the changes made 
        are only applied to what you see in the Web UI, not the ebook files themselves. This feature currently only supports files in EPUB 
        or AZW3 format.')}}
      </p>

      {% if cwa_settings['kindle_epub_fixer'] %}
      <input type="checkbox" id="kindle_epub_fixer" name="kindle_epub_fixer" value="True" checked style="accent-color: var(--color-secondary);" data-toggle="tooltip" data-placement="right" title="Does NOT require restart for changes to take effect">
      {% else %}
      <input type="checkbox" id="kindle_epub_fixer" name="kindle_epub_fixer" value="True" style="accent-color: var(--color-secondary);" data-toggle="tooltip" data-placement="right" title="Does NOT require restart for changes to take effect">
      {% endif %}
      <label for="kindle_epub_fixer" style="padding-left: 10px;">{{_('Enable CWA Kindle EPUB Fixer')}}</label><br>
      <p class="cwa-settings-tooltip">
        {{_("When active, the encoding among other attributes of all EPUB files processed by CWA will be checked and fixed to ensure maximum 
        compatibility with Amazon's Send-to-Kindle Service. This feature is particularly useful for users who frequently send EPUB files to their Kindle devices and have experienced issues with 
        file rejections or formatting problems.")}}
      <div style="margin-top: 1rem; padding: 0.5rem; background-color: rgba(255, 193, 7, 0.1); border-left: 4px solid #ffc107; border-radius: 0.25rem;">
        <small>{{_('This tool was adapted from the <a href=\"https://kindle-epub-fix.netlify.app/\">kindle-epub-fix.netlify.app</a> tool made by <a href=\"https://github.com/innocenat\">innocenat</a>.') | safe }}</small>
      </div>

      {% if cwa_settings['auto_metadata_fetch_enabled'] %}
      <input type="checkbox" id="auto_metadata_fetch_enabled" name="auto_metadata_fetch_enabled" value="True" checked style="accent-color: var(--color-secondary);" data-toggle="tooltip" data-placement="right" title="Automatically fetches metadata for newly ingested books">
      {% else %}
      <input type="checkbox" id="auto_metadata_fetch_enabled" name="auto_metadata_fetch_enabled" value="True" style="accent-color: var(--color-secondary);" data-toggle="tooltip" data-placement="right" title="Automatically fetches metadata for newly ingested books">
      {% endif %}
      <label for="auto_metadata_fetch_enabled" style="padding-left: 10px;">{{_('Enable Automatic Metadata Fetching for New Books')}}</label><br>
      <p class="cwa-settings-tooltip">
        {{_('When active, CWA will automatically attempt to fetch and apply metadata (title, author, description, cover, etc.) for newly ingested books using the configured metadata provider hierarchy. This helps improve the quality of book information, especially for books with poor or missing metadata.')}}
      </p>

      {% if cwa_settings['auto_metadata_smart_application'] %}
      <input type="checkbox" id="auto_metadata_smart_application" name="auto_metadata_smart_application" value="True" checked style="accent-color: var(--color-secondary);" data-toggle="tooltip" data-placement="right" title="Apply intelligent criteria when replacing existing metadata">
      {% else %}
      <input type="checkbox" id="auto_metadata_smart_application" name="auto_metadata_smart_application" value="True" style="accent-color: var(--color-secondary);" data-toggle="tooltip" data-placement="right" title="Apply intelligent criteria when replacing existing metadata">
      {% endif %}
      <label for="auto_metadata_smart_application" style="padding-left: 10px;">{{_('Enable Smart Metadata Application')}}</label><br>
      <p class="cwa-settings-tooltip">
        {{_('When enabled, fetched metadata will only replace existing data if it appears to be better quality (e.g., longer descriptions, higher resolution covers). When disabled, fetched metadata will replace existing data as-is from the preferred provider.')}}
      </p>

      <!-- Metadata Field Selection -->
      <div id="metadata-field-selection" style="margin-top: 20px; padding: 2rem; border: 1px solid transparent; border-radius: 6px; background-color: #1d28328a;">
        <h5 style="margin-bottom: 15px; color: var(--color-text);">📝 {{_('Metadata Fields to Update')}}</h5>
        <p class="cwa-settings-tooltip" style="margin-bottom: 15px; margin-left: 0px !important;">
          {{_('Select which metadata fields should be updated when auto-fetching. Unchecked fields will never be modified during automatic metadata fetching, preserving your existing data.')}}
        </p>
        
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 6px; padding: 2rem; margin-left: 1rem;">
          <!-- Title -->
          {% if cwa_settings['auto_metadata_update_title'] %}
          <div><input type="checkbox" id="auto_metadata_update_title" name="auto_metadata_update_title" value="True" checked style="accent-color: var(--color-secondary);"> <label for="auto_metadata_update_title">📖 {{_('Title')}}</label></div>
          {% else %}
          <div><input type="checkbox" id="auto_metadata_update_title" name="auto_metadata_update_title" value="True" style="accent-color: var(--color-secondary);"> <label for="auto_metadata_update_title">📖 {{_('Title')}}</label></div>
          {% endif %}
          
          <!-- Authors -->
          {% if cwa_settings['auto_metadata_update_authors'] %}
          <div><input type="checkbox" id="auto_metadata_update_authors" name="auto_metadata_update_authors" value="True" checked style="accent-color: var(--color-secondary);"> <label for="auto_metadata_update_authors">✍️ {{_('Authors')}}</label></div>
          {% else %}
          <div><input type="checkbox" id="auto_metadata_update_authors" name="auto_metadata_update_authors" value="True" style="accent-color: var(--color-secondary);"> <label for="auto_metadata_update_authors">✍️ {{_('Authors')}}</label></div>
          {% endif %}
          
          <!-- Description -->
          {% if cwa_settings['auto_metadata_update_description'] %}
          <div><input type="checkbox" id="auto_metadata_update_description" name="auto_metadata_update_description" value="True" checked style="accent-color: var(--color-secondary);"> <label for="auto_metadata_update_description">📝 {{_('Description')}}</label></div>
          {% else %}
          <div><input type="checkbox" id="auto_metadata_update_description" name="auto_metadata_update_description" value="True" style="accent-color: var(--color-secondary);"> <label for="auto_metadata_update_description">📝 {{_('Description')}}</label></div>
          {% endif %}
          
          <!-- Publisher -->
          {% if cwa_settings['auto_metadata_update_publisher'] %}
          <div><input type="checkbox" id="auto_metadata_update_publisher" name="auto_metadata_update_publisher" value="True" checked style="accent-color: var(--color-secondary);"> <label for="auto_metadata_update_publisher">🏢 {{_('Publisher')}}</label></div>
          {% else %}
          <div><input type="checkbox" id="auto_metadata_update_publisher" name="auto_metadata_update_publisher" value="True" style="accent-color: var(--color-secondary);"> <label for="auto_metadata_update_publisher">🏢 {{_('Publisher')}}</label></div>
          {% endif %}
          
          <!-- Tags -->
          {% if cwa_settings['auto_metadata_update_tags'] %}
          <div><input type="checkbox" id="auto_metadata_update_tags" name="auto_metadata_update_tags" value="True" checked style="accent-color: var(--color-secondary);"> <label for="auto_metadata_update_tags">🏷️ {{_('Tags/Genres')}}</label></div>
          {% else %}
          <div><input type="checkbox" id="auto_metadata_update_tags" name="auto_metadata_update_tags" value="True" style="accent-color: var(--color-secondary);"> <label for="auto_metadata_update_tags">🏷️ {{_('Tags/Genres')}}</label></div>
          {% endif %}
          
          <!-- Series -->
          {% if cwa_settings['auto_metadata_update_series'] %}
          <div><input type="checkbox" id="auto_metadata_update_series" name="auto_metadata_update_series" value="True" checked style="accent-color: var(--color-secondary);"> <label for="auto_metadata_update_series">📚 {{_('Series')}}</label></div>
          {% else %}
          <div><input type="checkbox" id="auto_metadata_update_series" name="auto_metadata_update_series" value="True" style="accent-color: var(--color-secondary);"> <label for="auto_metadata_update_series">📚 {{_('Series')}}</label></div>
          {% endif %}
          
          <!-- Rating -->
          {% if cwa_settings['auto_metadata_update_rating'] %}
          <div><input type="checkbox" id="auto_metadata_update_rating" name="auto_metadata_update_rating" value="True" checked style="accent-color: var(--color-secondary);"> <label for="auto_metadata_update_rating">⭐ {{_('Rating')}}</label></div>
          {% else %}
          <div><input type="checkbox" id="auto_metadata_update_rating" name="auto_metadata_update_rating" value="True" style="accent-color: var(--color-secondary);"> <label for="auto_metadata_update_rating">⭐ {{_('Rating')}}</label></div>
          {% endif %}
          
          <!-- Published Date -->
          {% if cwa_settings['auto_metadata_update_published_date'] %}
          <div><input type="checkbox" id="auto_metadata_update_published_date" name="auto_metadata_update_published_date" value="True" checked style="accent-color: var(--color-secondary);"> <label for="auto_metadata_update_published_date">📅 {{_('Publication Date')}}</label></div>
          {% else %}
          <div><input type="checkbox" id="auto_metadata_update_published_date" name="auto_metadata_update_published_date" value="True" style="accent-color: var(--color-secondary);"> <label for="auto_metadata_update_published_date">📅 {{_('Publication Date')}}</label></div>
          {% endif %}
          
          <!-- Identifiers -->
          {% if cwa_settings['auto_metadata_update_identifiers'] %}
          <div><input type="checkbox" id="auto_metadata_update_identifiers" name="auto_metadata_update_identifiers" value="True" checked style="accent-color: var(--color-secondary);"> <label for="auto_metadata_update_identifiers">🔢 {{_('Identifiers (ISBN, etc.)')}}</label></div>
          {% else %}
          <div><input type="checkbox" id="auto_metadata_update_identifiers" name="auto_metadata_update_identifiers" value="True" style="accent-color: var(--color-secondary);"> <label for="auto_metadata_update_identifiers">🔢 {{_('Identifiers (ISBN, etc.)')}}</label></div>
          {% endif %}
          
          <!-- Cover -->
          {% if cwa_settings['auto_metadata_update_cover'] %}
          <div><input type="checkbox" id="auto_metadata_update_cover" name="auto_metadata_update_cover" value="True" checked style="accent-color: var(--color-secondary);"> <label for="auto_metadata_update_cover">🖼️ {{_('Cover Image')}}</label></div>
          {% else %}
          <div><input type="checkbox" id="auto_metadata_update_cover" name="auto_metadata_update_cover" value="True" style="accent-color: var(--color-secondary);"> <label for="auto_metadata_update_cover">🖼️ {{_('Cover Image')}}</label></div>
          {% endif %}
        </div>
        
        <div style="margin-top: 1rem; padding: 0.5rem; background-color: rgba(255, 193, 7, 0.1); border-left: 4px solid #ffc107; border-radius: 0.25rem;">
          <small style="color: var(--color-info-text);">
            💡 <strong>{{_('Tip')}}:</strong> {{_('These field selections apply to both Smart and Direct replacement modes. Smart mode will additionally apply quality criteria to selected fields, while Direct mode will replace all selected fields with provider data.')}}
          </small>
        </div>
      </div>
    </div>

  <div class="settings-container">
    <!-- Ingest Timeout Setting -->
    <div class="form-group">
      <h4 class="settings-section-header">{{_('Ingest Processing Timeout')}}</h4>
      <p class="settings-description">
        {{_('Maximum time (in minutes) to allow for processing a single book before timing out. Files that timeout are moved to the failed backup folder for investigation.')}}
      </p>
      <label for="ingest_timeout_minutes" class="settings-section-header" style="padding-right: 10px; margin-bottom: 16px !important; padding-bottom: 0px !important;">{{_('Timeout (minutes):')}}</label>
      <input type="number" 
             name="ingest_timeout_minutes" 
             id="ingest_timeout_minutes" 
             value="{{ cwa_settings['ingest_timeout_minutes'] }}" 
             min="5" 
             max="120" 
             style="width: 100px;
                    padding: 5px;
                    border: 1px solid transparent;
                    border-radius: 4px;
                    background-color: #151e2680;">
      <small style="color: #bbbbbb; margin-left: 10px;">{{_('Range: 5-120 minutes (default: 15)')}}</small>
    </div>

    <!-- Auto-Send Delay Setting -->
    <div class="form-group">
      <h4 class="settings-section-header">{{_('Auto-Send Delay for New Books')}}</h4>
      <p class="settings-description">
        {{_('Delay (in minutes) before automatically sending newly ingested books to eReaders. This allows time for metadata fetching and other processing to complete before sending. Only applies to users who have enabled auto-send in their profile.')}}
      </p>
      <label for="auto_send_delay_minutes" class="settings-section-header" style="padding-right: 10px; margin-bottom: 16px !important; padding-bottom: 0px !important;">{{_('Delay (minutes):')}}</label>
      <input type="number" 
             name="auto_send_delay_minutes" 
             id="auto_send_delay_minutes" 
             value="{{ cwa_settings['auto_send_delay_minutes'] }}" 
             min="1" 
             max="60" 
             style="width: 100px;
                    padding: 5px;
                    border: 1px solid transparent;
                    border-radius: 4px;
                    background-color: #151e2680;">
      <small style="color: #bbbbbb; margin-left: 10px;">{{_('Range: 1-60 minutes (default: 5)')}}</small>
    </div>

    <!-- Metadata Provider Hierarchy Setting -->
    <div class="form-group">
      <h4 class="settings-section-header">{{_('Auto Metadata Fetch Provider Hierarchy')}}</h4>
      <p class="settings-description">
        {{_('Configure the order in which metadata providers are searched when automatically fetching metadata for new books. Drag and drop to reorder providers. Only enabled providers will be used.')}}
      </p>
      <div id="metadata_provider_hierarchy_container" style="margin-top: 15px;">
        <div id="metadata_provider_list_outer">
          <p style="text-align: center; margin-bottom: 20px;"><span style="font-weight: 900; color: #f8be03;">↥</span>&nbsp;&nbsp;Most Preferred</p>
          <div id="metadata_provider_list">
            <!-- Providers will be populated here by JavaScript -->
          </div>
          <p style="text-align: center; margin-top: 20px;"><span style="font-weight: 900; color: #f8be03;">↥</span>&nbsp;&nbsp;Least Preferred</p>
        </div>
        <input type="hidden" name="metadata_provider_hierarchy" id="metadata_provider_hierarchy_hidden" value="">
      </div>
      <div style="margin-top: 1rem; padding: 0.5rem; background-color: rgba(255, 193, 7, 0.1); border-left: 4px solid #ffc107; border-radius: 0.25rem;">
        <small class="settings-explanation">💡 <strong>{{_('Tip')}}:</strong> {{_('Providers are tried in order from top to bottom. Drag to reorder.')}}</small>
      </div>
    </div>

    </div>

    <div class="settings-container">
    <!-- Global Provider Enable/Disable Setting -->
      <div class="form-group">
        <h4 class="settings-section-header">{{_('Enabled Metadata Providers')}}</h4>
        <p class="settings-description">
          {{_('Unchecked providers are disabled globally.')}}
        </p>
        <div id="metadata_provider_enabled_container" style="margin-top: 10px;">
          <div id="metadata_provider_enabled_list">
            <!-- Provider toggles will be populated here by JavaScript -->
          </div>
          <input type="hidden" name="metadata_providers_enabled" id="metadata_providers_enabled_hidden" value="{}">
        </div>
      </div>
    </div>

    <div class="settings-container">
        <h4 class="settings-section-header">{{_('Web UI Settings')}}</h4>

      {% if cwa_settings['cwa_update_notifications'] %}
      <input type="checkbox" id="cwa_update_notifications" name="cwa_update_notifications" value="True" checked style="accent-color: var(--color-secondary);" data-toggle="tooltip" data-placement="right" title="Does NOT require restart for changes to take effect">
      {% else %}
      <input type="checkbox" id="cwa_update_notifications" name="cwa_update_notifications" value="True" style="accent-color: var(--color-secondary);" data-toggle="tooltip" data-placement="right" title="Does NOT require restart for changes to take effect">
      {% endif %}
      <label for="cwa_update_notifications" style="padding-left: 10px;">{{_('Enable CWA Update Notifications')}}</label><br>
      <p class="cwa-settings-tooltip">
        {{_('When active, you will receive notifications in the Web UI when a new version of CWA is released')}}
      </p>

      {% if cwa_settings['contribute_translations_notifications'] %}
      <input type="checkbox" id="contribute_translations_notifications" name="contribute_translations_notifications" value="True" checked style="accent-color: var(--color-secondary);" data-toggle="tooltip" data-placement="right" title="Does NOT require restart for changes to take effect">
      {% else %}
      <input type="checkbox" id="contribute_translations_notifications" name="contribute_translations_notifications" value="True" style="accent-color: var(--color-secondary);" data-toggle="tooltip" data-placement="right" title="Does NOT require restart for changes to take effect">
      {% endif %}
      <label for="contribute_translations_notifications" style="padding-left: 10px;">{{_('Enable Contribute Translations Notifications')}}</label><br>
      <p class="cwa-settings-tooltip">
        {{_('When disabled, you will no longer receive notifications in the Web UI when using a language other than English if the translations for your chosen language are not complete.')}}
      </p>

      {% if cwa_settings['enable_mobile_blur'] %}
      <input type="checkbox" id="enable_mobile_blur" name="enable_mobile_blur" value="True" checked style="accent-color: var(--color-secondary);" data-toggle="tooltip" data-placement="right" title="May impact performance on low-end mobile devices">
      {% else %}
      <input type="checkbox" id="enable_mobile_blur" name="enable_mobile_blur" value="True" style="accent-color: var(--color-secondary);" data-toggle="tooltip" data-placement="right" title="May impact performance on low-end mobile devices">
      {% endif %}
      <label for="enable_mobile_blur" style="padding-left: 10px;">{{_('Enable Blurred Backgrounds on Mobile (&lt;768px)')}}</label><br>
      <p class="cwa-settings-tooltip">
        {{_('When active, the blurred cover background effect is also rendered on small screens. Disable if you notice scrolling or animation lag.')}}
      </p>
    </div>

    <div class="settings-container">
      <h4 class="settings-section-header">{{_('Automatic Backup Settings')}}</h4>

      {% if cwa_settings['auto_backup_imports'] %}
      <input type="checkbox" id="auto_backup_imports" name="auto_backup_imports" value="True" checked style="accent-color: var(--color-secondary);" data-toggle="tooltip" data-placement="right" title="If deactivated, imported files can only be found in your Calibre Library" >
      {% else %}
      <input type="checkbox" id="auto_backup_imports" name="auto_backup_imports" value="True" style="accent-color: var(--color-secondary);" data-toggle="tooltip" data-placement="right" title="If deactivated, imported files can only be found in your Calibre Library" >
      {% endif %}
      <label for="auto_backup_imports" style="padding-left: 10px;">{{_('Enable CWA Import Auto-Backup')}}</label><br>
      <p class="cwa-settings-tooltip">
        {{_('When active, a copy of all imported files will be stored in <i>/config/processed_books/imported</i>') | safe }}
      </p>

      {% if cwa_settings['auto_backup_conversions'] %}
      <input type="checkbox" id="auto_backup_conversions" name="auto_backup_conversions" value="True" checked style="accent-color: var(--color-secondary);" data-toggle="tooltip" data-placement="right" title="If deactivated, the originals of converted files will not be stored (except in the case of a failed conversion)">
      {% else %}
      <input type="checkbox" id="auto_backup_conversions" name="auto_backup_conversions" value="True" style="accent-color: var(--color-secondary);" data-toggle="tooltip" data-placement="right" title="If deactivated, the originals of converted files will not be stored (except in the case of a failed conversion)">
      {% endif %}
      <label for="auto_backup_conversions" style="padding-left: 10px;">{{_('Enable CWA Conversion Auto-Backup')}}</label><br>
      <p class="cwa-settings-tooltip">
        {{_('When active, the originals of ingested files that undergo conversion will be stored in /config/processed_books/converted')}}
      </p>

      {% if cwa_settings['auto_backup_epub_fixes'] %}
      <input type="checkbox" id="auto_backup_epub_fixes" name="auto_backup_epub_fixes" value="True" checked style="accent-color: var(--color-secondary);" data-toggle="tooltip" data-placement="right" title="If deactivated, the originals of EPUB's that have been fixed will not be stored (except in the case of a process failure)">
      {% else %}
      <input type="checkbox" id="auto_backup_epub_fixes" name="auto_backup_epub_fixes" value="True" style="accent-color: var(--color-secondary);" data-toggle="tooltip" data-placement="right" title="If deactivated, the originals of EPUB's that have been fixed will not be stored (except in the case of a process failure)">
      {% endif %}
      <label for="auto_backup_epub_fixes" style="padding-left: 10px;">{{_('Enable CWA EPUB Fixer Auto-Backup')}}</label><br>
      <p class="cwa-settings-tooltip">
        {{_('When active, the originals of EPUBs processed by the CWA Kindle EPUB Fixer service will be stored in /config/processed_books/fixed_originals')}}
      </p>

      <hr class="settings-divider">

      {% if cwa_settings['auto_zip_backups'] %}
      <input type="checkbox" id="auto_zip_backups" name="auto_zip_backups" value="True" checked style="accent-color: var(--color-secondary);" data-toggle="tooltip" data-placement="right" data-html="true" title="If deactivated, backed up files will be left alone in their respective folders">
      {% else %}
      <input type="checkbox" id="auto_zip_backups" name="auto_zip_backups" value="True" style="accent-color: var(--color-secondary);" data-toggle="tooltip" data-placement="right" data-html="true" title="If deactivated, backed up files will be left alone in their respective folders">
      {% endif %}
      <label for="auto_zip_backups" style="padding-left: 10px;">{{_('Enable CWA Auto-Zip Backups')}}</label><br>
      <p class="cwa-settings-tooltip">
        {{_('When active, just before midnight each day, the cwa-auto-zipper service will make zip archives of all the backed up converted, imported and failed files from that day. This is to help keep the subdirectories of /config/processed_books organised and to minimise disk space usage.')}}
      </p>
    </div>
    
    <div class="settings-container">
      <h4 class="settings-section-header">{{_('CWA Auto-Conversion Target Format - EPUB by Default')}}</h4>

      <p class="cwa-settings-explanation settings-explanation">
        {{_('When the Auto-Convert feature is active, all ingested books will be automatically converted to the format chosen here (except those formats selected in the ignore list below)')}}
      </p>
      <label for="auto_convert_target_format" style="padding-right: 10px; margin-bottom: 16px !important;">{{_('Choose a target format:')}}</label>
      <select class="cwa-settings-select" name="auto_convert_target_format" id="auto_convert_target_format">
        {% for format in target_formats -%}
          {% if cwa_settings['auto_convert_target_format'] == format %}
            <option value="{{ format }}" selected>{{ format }}</option>
          {% else %}
            <option value="{{ format }}">{{ format }}</option>
          {% endif %}
        {% endfor %}
      </select>
      <div style="margin-top: 1rem; padding: 0.5rem; background-color: rgba(255, 193, 7, 0.1); border-left: 4px solid #ffc107; border-radius: 0.25rem;">
        <small class="settings-explanation">
          {{_("NOTE: CWA's Metadata Enforcement service can currently only support file in either EPUB and AZW3 format. Files in other formats will simply be ignored by the service")}}
        </small>
      </div>
    </div>

    <div class="settings-container">
      <h4 class="settings-section-header">{{_('CWA Auto-Convert - Ignored Formats')}}</h4>
      <p class="cwa-settings-explanation settings-explanation">
        {{_("The formats selected here will be ignored by CWA's Auto-Conversion feature when it's active, meaning they will be imported as is.")}}
      </p>
      <div style="max-width: 90rem; padding-left: 30px;">
        {% for format in ignorable_formats -%}
          <label for="ignore_convert_{{ format }}" style="width: 75px; padding-right: 6px; display: inline-block !important;">
            {% if format in cwa_settings['auto_convert_ignored_formats'] %}
              {% if format == cwa_settings['auto_convert_target_format'] %}
                <input type="checkbox" id="ignore_convert_{{ format }}" name="ignore_convert_{{ format }}" value="{{ format }}" disabled style="vertical-align: middle; accent-color: var(--color-secondary); display: inline-block !important;"">
              {% else %}
                <input type="checkbox" id="ignore_convert_{{ format }}" name="ignore_convert_{{ format }}" value="{{ format }}" checked style="vertical-align: middle; accent-color: var(--color-secondary); display: inline-block !important;"">
              {% endif %}
            {% else %}
              {% if format == cwa_settings['auto_convert_target_format'] %}
                <input type="checkbox" id="ignore_convert_{{ format }}" name="ignore_convert_{{ format }}" value="{{ format }}" disabled style="vertical-align: middle; accent-color: var(--color-secondary); display: inline-block !important;"">
              {% else %}
                <input type="checkbox" id="ignore_convert_{{ format }}" name="ignore_convert_{{ format }}" value="{{ format }}" style="vertical-align: middle; accent-color: var(--color-secondary); display: inline-block !important;"">
              {% endif %}
            {% endif %}
            <span style="padding-left: 4px; vertical-align: middle;">{{ format }}</span>
          </label>
        {% endfor %}
      </div>
    </div>

    <div class="settings-container">
      <h4 class="settings-section-header">{{_('CWA Auto-Convert - Retained Formats')}}</h4>
      <p class="cwa-settings-explanation settings-explanation">
        {{_('The formats selected here will always be added to the library, even after they have been converted to the target format. However, if the format is in the "CWA Auto-Ingest - Ignored Formats" list, it will not be imported. Note that the target format is always retained.')}}
      </p>
      <div style="max-width: 90rem; padding-left: 30px;">
        {% for format in ignorable_formats -%}
          <label for="convert_retained_{{ format }}" style="width: 75px; padding-right: 6px; display: inline-block !important;">
            {% if format in cwa_settings.get('auto_convert_retained_formats', []) or format == cwa_settings['auto_convert_target_format'] %}
              {% if format in cwa_settings['auto_ingest_ignored_formats'] %}
                <input type="checkbox" id="convert_retained_{{ format }}" name="convert_retained_{{ format }}" value="{{ format }}" disabled style="vertical-align: middle; accent-color: var(--color-secondary); display: inline-block !important;">
              {% elif format == cwa_settings['auto_convert_target_format'] %}
                <input type="checkbox" id="convert_retained_{{ format }}" name="convert_retained_{{ format }}" value="{{ format }}" checked disabled style="vertical-align: middle; accent-color: var(--color-secondary); display: inline-block !important;" title="Target format is always retained">
              {% else %}
                <input type="checkbox" id="convert_retained_{{ format }}" name="convert_retained_{{ format }}" value="{{ format }}" checked style="vertical-align: middle; accent-color: var(--color-secondary); display: inline-block !important;">
              {% endif %}
            {% else %}
              {% if format in cwa_settings['auto_ingest_ignored_formats'] %}
                <input type="checkbox" id="convert_retained_{{ format }}" name="convert_retained_{{ format }}" value="{{ format }}" disabled style="vertical-align: middle; accent-color: var(--color-secondary); display: inline-block !important;">
              {% else %}
                <input type="checkbox" id="convert_retained_{{ format }}" name="convert_retained_{{ format }}" value="{{ format }}" style="vertical-align: middle; accent-color: var(--color-secondary); display: inline-block !important;">
              {% endif %}
            {% endif %}
            <span style="padding-left: 4px; vertical-align: middle;">{{ format }}</span>
          </label>
        {% endfor %}
      </div>
    </div>

    <div class="settings-container">
      <h4 class="settings-section-header">{{_('CWA Auto-Ingest - Ignored Formats')}}</h4>
      <p class="cwa-settings-explanation settings-explanation">
        {{_("The formats selected here will be ignored by CWA's Auto-Ingest feature, meaning files in these formats won't be added to the library by CWA during the ingest process")}}
      </p>
      <div style="max-width: 90rem; padding-left: 30px;">
        {% for format in ignorable_formats -%}
          <label for="ignore_ingest_{{ format }}" style="width: 75px; padding-right: 6px; display: inline-block !important;">
            {% if format in cwa_settings['auto_ingest_ignored_formats'] %}
              {% if format == cwa_settings['auto_convert_target_format'] %}
                <input type="checkbox" id="ignore_ingest_{{ format }}" name="ignore_ingest_{{ format }}" value="{{ format }}" disabled style="vertical-align: middle; accent-color: var(--color-secondary); display: inline-block !important;"">
              {% else %}
                <input type="checkbox" id="ignore_ingest_{{ format }}" name="ignore_ingest_{{ format }}" value="{{ format }}" checked style="vertical-align: middle; accent-color: var(--color-secondary); display: inline-block !important;"">
              {% endif %}
            {% else %}
              {% if format == cwa_settings['auto_convert_target_format'] %}
                <input type="checkbox" id="ignore_ingest_{{ format }}" name="ignore_ingest_{{ format }}" value="{{ format }}" disabled style="vertical-align: middle; accent-color: var(--color-secondary); display: inline-block !important;"">
              {% else %}
                <input type="checkbox" id="ignore_ingest_{{ format }}" name="ignore_ingest_{{ format }}" value="{{ format }}" style="vertical-align: middle; accent-color: var(--color-secondary); display: inline-block !important;"">
              {% endif %}
            {% endif %}
            <span style="padding-left: 4px; vertical-align: middle;">{{ format }}</span>
          </label>
        {% endfor %}
      </div>
    </div>

<div class="settings-container">
      <h4 class="settings-section-header">{{_('CWA Auto-Ingest Automerge')}}</h4>

      <p class="cwa-settings-explanation settings-explanation">
        {{_('Calibre can detect Duplicate Book Titles on Import and depending on the')}} <code style="color: var(--color-secondary); background-color: #4e5254;">{{_('automerge')}}</code>
        {{_('setting. It can be set to delete either instance of a duplicated book or keep both (default).')}}
      </p>
      <label for="auto_ingest_automerge"  class="settings-section-header" style="padding-right: 10px; margin-bottom: 16px !important; padding-bottom: 0px !important;">Choose how to handle duplicates:</label>
      <select style="width: fit-content;" class="cwa-settings-select" name="auto_ingest_automerge" id="auto_ingest_automerge">
        {% for option in autoingest_options -%}
          {% if cwa_settings['auto_ingest_automerge'] == option %}
            <option value="{{ option }}" selected>{{ option }}</option>
          {% else %}
            <option value="{{ option }}">{{ option }}</option>
          {% endif %}
        {% endfor %}
      </select>

      <h4>Possible Values:</h4>
      <table style="width: -webkit-fill-available; margin-bottom: 2rem;">
        <tbody>
        <tr>
            <td><code style="color: var(--color-secondary); background-color: #4e5254;">ignore</code></td>
            <td>{{_('Discards duplicate import, keeps library copy')}}</td>
        </tr>
        <tr>
            <td><code style="color: var(--color-secondary); background-color: #4e5254;">overwrite</code></td>
            <td>{{_('Overwrites library copy with newly imported file')}}</td>
        </tr>
        <tr>
            <td><code style="color: var(--color-secondary); background-color: #4e5254;">new_record</code> (Default)</td>
            <td>{{_('Creates a duplicate record, keeping both copies')}}</td>
        </tr>
      </tbody></table>
    </div>

    <div class="settings-container">
      <h4 class="settings-section-header">{{_('CWA Duplicate Detection Criteria')}}</h4>

      <p class="cwa-settings-explanation settings-explanation">
        {{_('Configure which metadata fields are used to determine if books are duplicates. Books must match ALL selected criteria to be considered duplicates.')}}
      </p>

      <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 1rem; margin-top: 1rem;">
        <div class="checkbox-wrapper">
          <input type="checkbox" id="duplicate_detection_title" name="duplicate_detection_title" value="1" {% if cwa_settings['duplicate_detection_title'] %} checked {% endif %}>
          <label for="duplicate_detection_title">{{_('Title')}}</label>
          <small class="settings-explanation">{{_('Consider book titles when detecting duplicates')}}</small>
        </div>

        <div class="checkbox-wrapper">
          <input type="checkbox" id="duplicate_detection_author" name="duplicate_detection_author" value="1" {% if cwa_settings['duplicate_detection_author'] %} checked {% endif %}>
          <label for="duplicate_detection_author">{{_('Author')}}</label>
          <small class="settings-explanation">{{_('Consider book authors when detecting duplicates')}}</small>
        </div>

        <div class="checkbox-wrapper">
          <input type="checkbox" id="duplicate_detection_language" name="duplicate_detection_language" value="1" {% if cwa_settings['duplicate_detection_language'] %} checked {% endif %}>
          <label for="duplicate_detection_language">{{_('Language')}}</label>
          <small class="settings-explanation">{{_('Consider book language when detecting duplicates')}}</small>
        </div>

        <div class="checkbox-wrapper">
          <input type="checkbox" id="duplicate_detection_series" name="duplicate_detection_series" value="1" {% if cwa_settings['duplicate_detection_series'] %} checked {% endif %}>
          <label for="duplicate_detection_series">{{_('Series')}}</label>
          <small class="settings-explanation">{{_('Consider book series when detecting duplicates')}}</small>
        </div>

        <div class="checkbox-wrapper">
          <input type="checkbox" id="duplicate_detection_publisher" name="duplicate_detection_publisher" value="1" {% if cwa_settings['duplicate_detection_publisher'] %} checked {% endif %}>
          <label for="duplicate_detection_publisher">{{_('Publisher')}}</label>
          <small class="settings-explanation">{{_('Consider book publisher when detecting duplicates')}}</small>
        </div>

        <div class="checkbox-wrapper">
          <input type="checkbox" id="duplicate_detection_format" name="duplicate_detection_format" value="1" {% if cwa_settings['duplicate_detection_format'] %} checked {% endif %}>
          <label for="duplicate_detection_format">{{_('Format')}}</label>
          <small class="settings-explanation">{{_('Consider file format when detecting duplicates')}}</small>
        </div>
      </div>

      <div style="margin-top: 1rem; padding: 0.5rem; background-color: rgba(255, 193, 7, 0.1); border-left: 4px solid #ffc107; border-radius: 0.25rem;">
        <small class="settings-explanation">
          <strong>{{_('Note:')}}</strong> {{_('At least one criterion must be selected. Title and Author are recommended as core criteria.')}}
        </small>
      </div>
    </div>

    <br>

    <br>
    <div style="margin-top: -2rem; max-width: 900px; justify-self: center; margin-bottom: 1rem; display: flex; flex-direction: row; flex-wrap: wrap; width: -webkit-fill-available; justify-content: space-between; margin-left: 2rem; margin-right: 2rem;">
      <input type="submit" name="submit_button" value="Submit" class="btn btn-default">
      <input type="submit" name="submit_button" value="Apply Default Settings" class="btn btn-default">
    </div>
    <br>

    </div>
  </form>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
  // Get current hierarchy from CWA settings
  const currentHierarchyStr = {{ cwa_settings.get("metadata_provider_hierarchy", '["ibdb","google","dnb"]') | tojson }};
  let providerHierarchy = [];
  // Get current global enabled map from CWA settings
  const currentEnabledStr = {{ cwa_settings.get("metadata_providers_enabled", '{}') | tojson }};
  let globalEnabledMap = {};
  
  try {
    if (typeof currentHierarchyStr === 'string') {
      providerHierarchy = JSON.parse(currentHierarchyStr);
    } else {
      providerHierarchy = currentHierarchyStr;
    }
  } catch (e) {
    console.error('Error parsing hierarchy:', e);
    providerHierarchy = ["ibdb", "google", "dnb"]; // fallback
  }

  try {
    if (typeof currentEnabledStr === 'string') {
      const s = currentEnabledStr.startsWith("'") && currentEnabledStr.endsWith("'")
        ? currentEnabledStr.slice(1, -1) : currentEnabledStr;
      globalEnabledMap = JSON.parse(s || '{}');
    } else {
      globalEnabledMap = currentEnabledStr || {};
    }
    if (typeof globalEnabledMap !== 'object' || Array.isArray(globalEnabledMap)) {
      globalEnabledMap = {};
    }
  } catch (e) {
    console.error('Error parsing enabled map:', e);
    globalEnabledMap = {};
  }
  
  // Fetch available providers from the API (use correct app base URL)
  fetch('{{ url_for("metadata.metadata_provider") }}')
    .then(response => response.json())
    .then(providers => {
      populateProviderList(providers, providerHierarchy);
      populateEnabledToggles(providers, globalEnabledMap);
      setupDragAndDrop();
    })
    .catch(error => {
      console.error('Error fetching providers:', error);
      // Fallback with static list
      const fallbackProviders = [
        {id: 'google', name: 'Google Books', active: true},
        {id: 'dnb', name: 'DNB', active: true},
        {id: 'ibdb', name: 'IBDb', active: true},
        {id: 'comicvine', name: 'ComicVine', active: true},
        {id: 'douban', name: 'Douban', active: true}
      ];
      populateProviderList(fallbackProviders, providerHierarchy);
      populateEnabledToggles(fallbackProviders, globalEnabledMap);
      setupDragAndDrop();
    });
  
  function populateProviderList(providers, hierarchy) {
    const container = document.getElementById('metadata_provider_list');
    const hiddenInput = document.getElementById('metadata_provider_hierarchy_hidden');
    
    // Clear any existing content
    container.innerHTML = '';
    
    // Create a map of providers by ID for easy lookup
    const providerMap = {};
    providers.forEach(p => {
      providerMap[p.id] = p;
    });
    
    // First add providers in the current hierarchy order (this is the saved user preference)
    hierarchy.forEach(providerId => {
      if (providerMap[providerId]) {
        addProviderItem(container, providerMap[providerId]);
        delete providerMap[providerId]; // Remove so we don't add twice
      }
    });
    
    // Then add any remaining providers that weren't in the hierarchy (new providers)
    // These will be added in the order they come from the API (alphabetical)
    Object.values(providerMap).forEach(provider => {
      addProviderItem(container, provider);
    });
    
    updateHiddenInput();
  }
  
  function addProviderItem(container, provider) {
    const item = document.createElement('div');
    item.className = 'metadata-provider-item';
    item.draggable = false; // Disable native drag
    item.dataset.providerId = provider.id;
    
    // For admin settings, show all providers as enabled/available
    item.innerHTML = `
      <span class="metadata-provider-drag-handle">⋮⋮</span>
      <span class="metadata-provider-name">
        ${provider.name}
      </span>
    `;
    
    container.appendChild(item);
  }

  function populateEnabledToggles(providers, enabledMap) {
    const container = document.getElementById('metadata_provider_enabled_list');
    const hidden = document.getElementById('metadata_providers_enabled_hidden');
    container.innerHTML = '';
    providers.forEach(p => {
      const wrapper = document.createElement('div');
      wrapper.classList.add('provider_enable_item');

      const id = `global-provider-${p.id}`;
      const checked = (enabledMap.hasOwnProperty(p.id) ? !!enabledMap[p.id] : true);
      wrapper.innerHTML = `
        <input type="checkbox" id="${id}" data-provider-id="${p.id}" ${checked ? 'checked' : ''}>
        <label for="${id}" style="margin-left: 8px;">${p.name}</label>
      `;
      container.appendChild(wrapper);
    });

    function updateHidden() {
      const toggles = container.querySelectorAll('input[type="checkbox"][data-provider-id]');
      const map = {};
      toggles.forEach(t => {
        map[t.dataset.providerId] = !!t.checked;
      });
      hidden.value = JSON.stringify(map);
    }

    container.addEventListener('change', updateHidden);
    updateHidden();

    // Ensure the hidden input is up to date on submit
    const form = document.querySelector('form[action$="/cwa-settings"]');
    if (form) {
      form.addEventListener('submit', updateHidden);
    }
  }
  
  function setupDragAndDrop() {
    const container = document.getElementById('metadata_provider_list');
    let draggedElement = null;
    let isDragging = false;
    let startY = 0;
    let startX = 0;
    
    container.addEventListener('mousedown', function(e) {
      const item = e.target.closest('.metadata-provider-item');
      if (!item) return;
      
      draggedElement = item;
      isDragging = true;
      startY = e.clientY;
      startX = e.clientX;
      
      item.classList.add('dragging');
      document.body.style.userSelect = 'none';
      
      e.preventDefault();
    });
    
    document.addEventListener('mousemove', function(e) {
      if (!isDragging || !draggedElement) return;
      
      const container = document.getElementById('metadata_provider_list');
      const afterElement = getMouseAfterElement(container, e.clientY);
      
      if (afterElement == null) {
        container.appendChild(draggedElement);
      } else {
        container.insertBefore(draggedElement, afterElement);
      }
    });
    
    document.addEventListener('mouseup', function(e) {
      if (!isDragging) return;
      
      isDragging = false;
      if (draggedElement) {
        draggedElement.classList.remove('dragging');
        draggedElement = null;
      }
      document.body.style.userSelect = '';
      updateHiddenInput();
    });
  }
  
  function getMouseAfterElement(container, y) {
    const draggableElements = [...container.querySelectorAll('.metadata-provider-item:not(.dragging)')];
    
    return draggableElements.reduce((closest, child) => {
      const box = child.getBoundingClientRect();
      const offset = y - box.top - box.height / 2;
      
      if (offset < 0 && offset > closest.offset) {
        return { offset: offset, element: child };
      } else {
        return closest;
      }
    }, { offset: Number.NEGATIVE_INFINITY }).element;
  }
  
  function updateHiddenInput() {
    const container = document.getElementById('metadata_provider_list');
    const hiddenInput = document.getElementById('metadata_provider_hierarchy_hidden');
    const items = container.querySelectorAll('.metadata-provider-item');
    
    const hierarchy = Array.from(items).map(item => item.dataset.providerId);
    hiddenInput.value = JSON.stringify(hierarchy);
  }
  
  // Initialize the hidden input value
  updateHiddenInput();
});
</script>
{% endblock %}
